package pe.com.cotelasa.scp.dominio.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.primefaces.model.UploadedFile;
import pe.com.cotelasa.scp.dominio.excepcion.ServiceException;

public class UtilitarioArchivos {

    public static void copyInputStream(InputStream in, File dest) throws IOException {
        if (!dest.exists()) {
            dest.createNewFile();
        }
        OutputStream out = null;
        try {
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            in.close();
            out.close();
        }
    }

    public static void copyFile(File source, File dest) throws IOException {
        if (!dest.exists()) {
            dest.createNewFile();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            in.close();
            out.close();
        }
    }

    public static boolean delete(File resource) throws IOException {
        if (resource.isDirectory()) {
            File[] childFiles = resource.listFiles();
            for (File child : childFiles) {
                delete(child);
            }
        }
        return resource.delete();
    }

    public static boolean guardarImagenServer(UploadedFile fileLogo, String logo) throws ServiceException {
        try {
            File archivoLogo = new File(logo);
            if (archivoLogo != null) {
                if (archivoLogo.exists()) {
                    delete(archivoLogo);
                }
            }
            copyInputStream(fileLogo.getInputstream(), archivoLogo);
            return true;
        } catch (IOException e) {
            throw new ServiceException(e);
        }

    }

    public static boolean eliminarImagenServer(String logo) throws ServiceException {
        try {
            File archivoLogo = new File(logo);
            if (archivoLogo != null) {
                if (archivoLogo.exists()) {
                    delete(archivoLogo);
                }
            }
            return true;
        } catch (IOException e) {
            throw new ServiceException(e);
        }

    }
}
